package utils

import (
	"reflect"
	"fmt"
	"errors"
	"strings"
)

// get请求数据组装
func AppendGET(data interface{}) (string, error) {
	//get 请求,
	val := reflect.ValueOf(data)
	if val.Kind() != reflect.Ptr {
		return "", errors.New("The struct paramer must be use ptr")
	}
	el := val.Elem()
	if !el.IsValid() {
		return "", errors.New("data err")
	}
	queryTag := "query"
	formTag := "form"
	var queryStr = "?"
	for i := 0; i < el.Type().NumField(); i++ {
		name := el.Type().Field(i).Tag.Get(queryTag)
		if name == "" {
			name = el.Type().Field(i).Tag.Get(formTag)
		}
		if name == "" {
			continue
		}
		value := getValue(el.Field(i))
		if value == "" {
			continue
		}
		if queryStr != "?" {
			queryStr += "&"
		}
		queryStr += name + "=" + value
	}
	return queryStr, nil
}

// 获取值
func getValue(value reflect.Value) string {
	switch value.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		temp := value.Int()
		return fmt.Sprintf("%d", temp)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		temp := value.Uint()
		return fmt.Sprintf("%d", temp)
	case reflect.Float32, reflect.Float64:
		temp := value.Float()
		return fmt.Sprintf("%f", temp)
	case reflect.String:
		return value.String()
	}
	return ""
}

// http://47nfdgw.bx3618.com/x/x --> http://47nfdgw.bx3618.com
func GetOrigin(url string) string {
	index := strings.Index(url, ".com")
	if index <= 0 {
		return ""
	}
	return url[:index+4]
}

// http://47nfdgw.bx3618.com/x/x --> 47nfdgw.bx3618.com
func GetHost(url string) string {
	url = GetOrigin(url)
	if url == "" {
		return ""
	}
	return strings.Replace(url, "http://", "", 1)
}
